import os
import Constant
from Tools import VectorCollector
import ParaSplit
from sklearn.linear_model import LassoCV
import numpy as np
import json
import joblib
import matplotlib.pyplot as plt
from tkinter import *
import tkinter.messagebox

init=False
reg=None
fans=None
def Init():
    global init,reg,fans
    if init:
        return 
    reg=joblib.load('Cache/model.pkl')
    #print(reg.get_params())
    fans=[]
    init=True
#print(reg.n_features_in_)
def GetArticleScore(s,name):
    Init()
    ss=ParaSplit.ParaSplit(s)
#    print("len=",len(s),' ',len(ss))
    if len(ss)<2:
        return('文章长度太短')
    else:
        ans=0
        tot=0
        lis=[]
        sum=len(ss)
        for x in ss:
            try:
                tp=reg.predict([np.array(VectorCollector.GetVector(x))])[0]
                ans+=tp
                lis.append(tp)
            except BaseException as e:
                print(x)
                print(e)
                sum-=1
            tot+=1
            print(str(tot)+'/'+str(len(ss)))
        fans.append([name,lis])
        return ans/sum
            
def GetScore(s):
    if len(s.strip())<2:
        return '文本长度太短'
    Init()
    vtr=VectorCollector.GetVtr(s)
    return reg.predict([np.array(vtr)])[0]
'''
f=open('in.txt','r',encoding='utf-8')
print(GetArticleScore(f.read()))
f.close()
'''

def GetScoreOfLocalFile():
    lis=os.listdir('Data/Test')
    for x in lis:
        f=open('Data/Test/'+x,'r',encoding='utf-8')
        print(str(GetArticleScore(f.read(),x))+' '+x)
        f.close()
    for x in fans:
        print(x[0])
        print(x[1])
    for i in range(0,len(fans)):
            plt.plot([j/(len(fans[i][1])-1) for j in range(0,len(fans[i][1]))],fans[i][1],label=fans[i][0]+', avg: '+str(sum(fans[i][1])/len(fans[i][1])))
    plt.legend(ncol=1)
    plt.show()
def OnClick(E1,root,b):
    if b==False:
        ans=GetArticleScore(E1.get('1.0','end'),'Text')
    else:
        ans=GetScore(E1.get('1.0','end'))
    if isinstance(ans,str):
        print('Error')
        tkinter.messagebox.showwarning('警告',ans)
    else:
        if isinstance(ans,float):
            tkinter.messagebox.showinfo('正式程度',str(ans))
            return
        global fans
        for i in range(0,len(fans)):
            plt.plot([j/(len(fans[i][1])-1) for j in range(0,len(fans[i][1]))],fans[i][1],label=fans[i][0]+', avg: '+str(sum(fans[i][1])/len(fans[i][1])))
        plt.legend(ncol=1)
        plt.show()
        fans=[]

def EvalWindow():

    root=Tk()
    root.title('英语文本正式程度评估')
    root.geometry('640x480')
    L1 = Label(root, text="需评估的文本")
    L1.pack()
    E1 =Text(root,width=480,height=25)
    E1.pack()
        
    B=Button(root,text='评估长文章',command=lambda : OnClick(E1,root,False))
    B1=Button(root,text='评估短文段',command=lambda : OnClick(E1,root,True))
    B.pack()
    B1.pack()
    mainloop()

def main():
    EvalWindow()
# 增加调用main()函数
if __name__ == '__main__':
    main()
